package api;

import Dao.Blog;
import Dao.BlogDao;
import Dao.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import common.Common;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;

@WebServlet("/update")
public class UpdateServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    private int BlogId = 0;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");
        User user = Common.checkLoginStatus(req);
        if(user == null){
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write("<script>alert('当前未登录')</script>");
            return;
        }

        String blogId = req.getParameter("blogId");
        if(blogId == null || "".equals(blogId)){
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write("<script>alert('blogId丢失')</script>");
        }
        BlogId = Integer.parseInt(blogId);

        BlogDao blogDao = new BlogDao();
        Blog blog = blogDao.selectOne(Integer.parseInt(blogId));
        resp.getWriter().write(objectMapper.writeValueAsString(blog));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf8");

        User user = Common.checkLoginStatus(req);
        if(user == null){
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write("<script>alert('当前未登录')</script>");
            return;
        }
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        if(title == null || "".equals(title) || content == null || "".equals(content)){
            resp.getWriter().write("<script>alert('有内容为空')</script>");
            return;
        }

        int blogId = BlogId;

        BlogDao blogDao = new BlogDao();
        Blog blog = new Blog();
        blog.setPostTime(new Timestamp(System.currentTimeMillis()));
        blog.setTitle(title);
        blog.setContent(content);
        blog.setBlogId(blogId);
        blogDao.update(blog);

        resp.sendRedirect("home.html");
    }
}
